import { ref } from 'vue'

export function useAsyncData(loader, options = {}) {
  const {
    initialValue = null,
    immediate = false,
    transform,
    onError,
    onSuccess,
  } = options

  const data = ref(initialValue)
  const loading = ref(false)
  const error = ref('')

  const execute = async (...args) => {
    loading.value = true
    error.value = ''
    try {
      const result = await loader(...args)
      const value = typeof transform === 'function' ? transform(result) : result
      data.value = value
      if (typeof onSuccess === 'function') {
        onSuccess(value)
      }
      return value
    } catch (err) {
      const message = err?.message || '数据加载失败'
      error.value = message
      if (typeof onError === 'function') {
        onError(err)
      }
      throw err
    } finally {
      loading.value = false
    }
  }

  if (immediate) {
    // eslint-disable-next-line promise/catch-or-return
    execute()
  }

  return {
    data,
    loading,
    error,
    execute,
    refresh: execute,
  }
}

